package com.unam.agenda;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DatabaseAdapter {
	
	public static final String KEY_ROWID="codigo";
	public static final String KEY_NAME="nombre";
	public static final String KEY_TELEPHONE="telefono";
	public static final String DATABASE_TABLE="contacto";
	private Context context;
	private SQLiteDatabase database;
	private Database dbHelper;

	
	public DatabaseAdapter(Context context){
		this.context=context;
	}
	
	public DatabaseAdapter open() throws SQLException{
		dbHelper=new Database(context);
		database=dbHelper.getWritableDatabase();
		return this;
	}
	
	public void close(){
		dbHelper.close();
	}
	
	public long creaRegistro(String name,String telephone){
		ContentValues initialValues=createContentValues(name, telephone);
		return database.insert(DATABASE_TABLE, null, initialValues);
	}
	
	public boolean updateAgenda(long rowId,String name,String telephone){
		ContentValues updateValues=createContentValues(name, telephone);
		String condicion=KEY_ROWID+"="+rowId;
		int rows=database.update(DATABASE_TABLE, updateValues, condicion, null);
		if(rows>0)
			return true;
		else 
			return false;
		
	}
	
	public boolean deleteAgenda(long rowId){
		
		String condicion=KEY_ROWID + "=" + rowId;
		int rows=database.delete(DATABASE_TABLE, condicion, null);
		if(rows>0)
			return true;
		else 
			return false;
	}
	
	public boolean deleteTodo(){
		
		int rows=database.delete(DATABASE_TABLE, "1", null);
		if(rows>0)
			return true;
		else 
			return false;
	}
	
	public Cursor todosContactos(){
		
		String [] columns=new String[]{KEY_ROWID,
				KEY_NAME,KEY_TELEPHONE};
		return database.query(DATABASE_TABLE, columns, null, null, null, null, null);
		
	}
	
	public int getContact(String name) throws SQLException{
		
		String [] columns=new String[]{KEY_ROWID,
				KEY_NAME,KEY_TELEPHONE};
		String selection=KEY_NAME + "='" + name+"'";
		
		Cursor mCursor=database.query(true, DATABASE_TABLE, columns, selection, null, null, null, null, null);
		
		int id=-1;
		if(mCursor !=null){
			
			mCursor.moveToFirst();
			id=mCursor.getInt(0);
		}
		return id;
	}
	
	private ContentValues createContentValues(String name,String telephone){
		ContentValues values=new ContentValues();
		values.put(KEY_NAME, name);
		values.put(KEY_TELEPHONE, telephone);
		return values;
	}
	

}
